package com.maimang.platform.activiti.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.maimang.platform.activiti.dto.ModelEntityDto;
import com.maimang.platform.activiti.service.ActModelService;
import com.maimang.platform.annotation.Log;
import com.maimang.platform.base.BaseController;
import com.maimang.platform.base.Result;
import com.maimang.platform.enums.BusinessType;
import com.maimang.platform.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.impl.persistence.entity.ModelEntity;
import org.activiti.engine.repository.Model;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import static org.activiti.editor.constants.ModelDataJsonConstants.MODEL_DESCRIPTION;
import static org.activiti.editor.constants.ModelDataJsonConstants.MODEL_NAME;

/**
 * @author Rocky
 * @version 1.0.0
 * @classname ActModelController
 * @description 模型管理
 * @date 2019-04-22 20:07
 * @email jintaozhao@qq.com
 */
@Controller
@RequestMapping("/activiti/model")
@Api(value = "模型管理", description = "activiti模型管理操作接口")
public class ActModelController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(ActModelController.class);

	private String prefix = "activiti/model";

	@Autowired
	private ActModelService actModelService;

	@Autowired
	private ObjectMapper objectMapper;

	/**
	 * 进入模型列表页
	 *
	 * @return
	 */
	@RequiresPermissions("activiti:model:view")
	@GetMapping
	public String model() {
		return prefix + "/model";
	}

	@RequiresPermissions("activiti:model:view")
	@GetMapping("/hello")
	public String helloModel(org.springframework.ui.Model model) {
		model.addAttribute("name", "Rocky");
		model.addAttribute("today", "今天是2019年5月6日，星期一，西安有雨");
		model.addAttribute("model", "这个只是model测试页面，activiti:model:view");
		return prefix + "/index";
	}

	@ApiOperation(value = "模型列表")
	@RequiresPermissions("activiti:model:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(ModelEntityDto modelEntityDto) {
		return actModelService.selectModelList(modelEntityDto);
	}


	@GetMapping("/add")
	public String add() throws UnsupportedEncodingException {
		ModelEntity model = new ModelEntity();
		String name = "new-process";
		String description = "新的流程";
		int revision = 1;
		String key = "process";
		ObjectNode modelNode = objectMapper.createObjectNode();
		modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
		modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
		modelNode.put(ModelDataJsonConstants.MODEL_REVISION, revision);
		model.setName(name);
		model.setKey(key);
		model.setMetaInfo(modelNode.toString());
		String modelId = actModelService.createModel(model);
		return redirect("/modeler.html?modelId=" + modelId);
	}

	@GetMapping("/{modelId}/json")
	@ResponseBody
	public ObjectNode getEditorJson(@PathVariable String modelId) {
		ObjectNode modelNode = actModelService.selectWrapModelById(modelId);
		return modelNode;
	}


	@GetMapping("/edit/{modelId}")
	public String edit(@PathVariable("modelId") String modelId) {
		return redirect("/modeler.html?modelId=" + modelId);
	}


	@Log(title = "删除模型", businessType = BusinessType.DELETE)
	@RequiresPermissions("activiti:model:remove")
	@PostMapping("/remove")
	@ResponseBody
	public Result remove(String ids) {
		return toResult(actModelService.deleteModelIds(ids));
	}

	/**
	 * 发布流程
	 *
	 * @param modelId
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "发布流程", notes = "根据传入的模型modelId发布流程")
	@Log(title = "发布流程", businessType = BusinessType.UPDATE)
	@RequiresPermissions("activiti:model:deploy")
	@GetMapping("/deploy/{modelId}")
	@ResponseBody
	public Result deploy(@PathVariable("modelId") String modelId) throws Exception {
		return actModelService.deployProcess(modelId);
	}

	@ApiOperation(value = "保存模型", notes = "保存模型的相关数据：id,name,description,json,svg")
	@Log(title = "模型管理", businessType = BusinessType.UPDATE)
	@PutMapping(value = "/{modelId}/save")
	@ResponseBody
	public void save(@PathVariable String modelId, String name, String description, String json_xml,
	                 String svg_xml) throws IOException, TranscoderException {
		Model model = actModelService.selectModelById(modelId);
		ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
		modelJson.put(MODEL_NAME, name);
		modelJson.put(MODEL_DESCRIPTION, description);
		model.setMetaInfo(modelJson.toString());
		model.setName(name);
		actModelService.update(model, json_xml, svg_xml);
	}

	@ApiOperation(value = "导出模型", notes = "根据模型id导出指定模型xml文件")
	@Log(title = "导出指定模型", businessType = BusinessType.EXPORT)
	@RequiresPermissions("activiti:model:export")
	@RequestMapping("/export/{id}")
	public void exportToXml(@PathVariable("id") String id, HttpServletResponse response) {
		try {
			Model modelData = actModelService.selectModelById(id);
			BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
			JsonNode editorNode = new ObjectMapper().readTree(actModelService.getModelEditorSource(modelData.getId()));
			BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
			BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
			byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel);

			ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);
			IOUtils.copy(in, response.getOutputStream());
			String filename = bpmnModel.getMainProcess().getId() + ".bpmn20.xml";
			response.setHeader("Content-Disposition", "attachment; filename=" + filename);
			response.flushBuffer();
		} catch (Exception e) {
			throw new ActivitiException("导出model的xml文件失败，模型ID=" + id, e);
		}
	}
}
